package com.ysstech.gateway.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.context.RequestContext;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.User;
import com.ysstech.common.util.SpringContextUtil;
import com.ysstech.common.util.StringUtil;
import com.ysstech.common.util.TokenUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Token过滤器
 */
public class TokenFilter extends ZuulFilter {
    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        return "pre";   //表示在请求之前执行
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    //判断过滤器是否生效
    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 不验证token的请求
    private String[] urlArry = {"userlogin", "getSessioniCode"};

    @Override
    public Object run() throws ZuulException {
        try {
            //获取当前请求上下文，在这个上下文基础上可以做很多事情了。具体自己查看API。
            RequestContext context = RequestContext.getCurrentContext();
            //获取原始Htpp请求，有这个对象也可以做很多事情了。自己发挥吧。
            HttpServletRequest request = context.getRequest();
            HttpServletResponse response = context.getResponse();
            //获取全部参数
            StringBuffer url = request.getRequestURL();
            log.info("Request请求URL->" + request.getRequestURL());
            // 放行登录请求
            if (StringUtil.oneOf(url.toString(), urlArry)) {
                context.setSendZuulResponse(true); //将请求往后转发
                context.setResponseStatusCode(200);
                return null;
            }
            //如果没有登录，shiro会跳转首页
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            // 被踢出的用户
            if ("2".equals(session.getAttribute("kickout"))) {
                //会话被踢出了
                session.removeAttribute("kickout");
                response.sendRedirect("/api-system/userlogin/index?kickout=2");
                return null;
            }
            //判断token的正确性
            String token = (String) subject.getPrincipal();
            RedisCacheManager redisCacheManager = SpringContextUtil.getBean(RedisCacheManager.class);
            String json = (String) redisCacheManager.getCache(token);
            User userinfo = JSONArray.parseObject(json, User.class);
            if (null == userinfo || !TokenUtil.getKey(token).equals(userinfo.getId())) {
                response.sendRedirect("/api-system/userlogin/index?kickout=1");
                return null;
            }
        } catch (Exception ex) {
            log.error("token过滤器异常：" + ex.toString());
        }
        //否则正常执行 调用服务接口...
        return null;
    }
}
